package com.lyh.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lyh.pojo.Role;
import com.lyh.pojo.User;
import com.lyh.service.role.RoleService;
import com.lyh.service.user.UserService;
import com.lyh.utils.Constants;
import com.lyh.utils.PageSupport;
import com.mysql.cj.util.StringUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {


    public UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }


    @RequestMapping("/login")
    @ResponseBody
    public User Login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 获取login页面的表单数据：userCode，userPassword
        String userCode = request.getParameter("userCode");
        String userPassword = request.getParameter("userPassword");

        if (userCode == null || userPassword == null) return null;
        // 把表单的数据 放进 工具map里
        Map<String, String> map = new HashMap<>();
        map.put("userCode",userCode);
        map.put("userPassword",userPassword);

        // 使用工具map，完成业务操作

        return userService.checkLogin(map);

/*        if (user != null ) {
            // 如果验证通过，往session中存放{"userSession":user}
            request.getSession().setAttribute(Constants.USER_SESSION,user);
            //请求转发到 frame页面
            request.getRequestDispatcher("/WEB-INF/jsp/frame.jsp").forward(request,response);

        } else {

            // 如果验证未通过 给前端返回一个error信息
            request.setAttribute("error","用户名或者密码不正确");
            *//*response.sendRedirect("/login.jsp");*//*
            //请求转发到 login页面，并显示 error 信息
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }*/

    }

    @GetMapping("/userList")
    public String search(HttpServletRequest request, Model model) {

        // 获取userService
        // UserService userService = Constants.context.getBean("userService", UserService.class);

        // 模糊查询的 userName
        String userName = request.getParameter("queryname");
        // 要查询的RoleId
        String RoleId = request.getParameter("queryUserRole");
        // 查询出来的数据，需要显示第几页
        String pageNo = request.getParameter("pageIndex");
        // 工具roleid
        int roleid = 0;

        // 当第一次走这个页面的时候
        // 默认设置页面显示ui数是6
        int PageSize = 6;
        //默认显示第一页
        int currentPageNo = 1;

        /* 刚进来的时候，UserName=null, RoleId=null, currentPageNo=1;所以默认查询所有值*/
        /* 第二次进入该网页会更新这三个数据，使用动态sql语句，进行选择查询*/

        //创建一个工具 map
        Map<String, Object> map = new HashMap<>();

        if (userName!=null&&!userName.equals("")) {
            // 如果userName不为空，就把userName头尾的空格去掉，加入map
            map.put("userName",userName.trim());
        } else {
            // 如果userName为空，就把null存进工具map
            map.put("userName",null);
        }

        if (RoleId != null&&!RoleId.equals("")) {
            // 如果RoleId不为空，就把RoleId里的int数据放入roleid，加入map
            roleid = Integer.parseInt(RoleId);
            map.put("userRole",roleid);
        } else {
            // 如果RoleId为空，就把默认的roleid=0加入map
            map.put("userRole",roleid);
        }

        if (pageNo!=null&&!pageNo.equals("")) {
            // 如果有指定pageNo，pageNo不为空，就设置currentPageNo；
            // currentPageNo默认为1
            currentPageNo = Integer.parseInt(pageNo);
        }

        /*计算分页功能：上一页，下一页，首页，尾页，跳到第几页*/
        //1.首先获取用户查询数量
        int userCount = userService.getUserCount(map);

        //2.利用工具类PageSupport计算页码，总页数
        PageSupport pageSupport = new PageSupport();
        //设置每页页面显示个数， PageSize默认6个
        pageSupport.setPageSize(PageSize);
        //设置需要显示的总数，setTotalCount方法可以根据页面大小计算出总页数
        pageSupport.setTotalCount(userCount);
        //设置当前页面页码
        pageSupport.setCurrentPageNo(currentPageNo);
        //获得总页数
        int totalPageCount = pageSupport.getTotalPageCount();

        //控制首页和尾页的正常值
        if(currentPageNo<1){
            currentPageNo=1;
        }else if(currentPageNo>totalPageCount){
            currentPageNo=totalPageCount;
        }

        // 计算需要显示的数据的开始下标

        map.put("currentPageNo",(currentPageNo-1)*PageSize);
        // 设置从该下标起显示个数
        map.put("PageSize",PageSize);

        // 进行查询操作，返回userList
        List<User> userList = userService.getUserListByNameAndRole(map);
        // 把userList存入model返回给前端
        model.addAttribute("userList",userList);

        // 查询所有role信息
        RoleService roleService = Constants.context.getBean("roleService", RoleService.class);
        List<Role> roleList = roleService.getRoleList();
        // 把roleList返回前端，前端通过判断显示
        model.addAttribute("roleList",roleList);

        /*返回一些前端需要的参数*/
        // 刚刚模糊查询的 userName
        request.setAttribute("queryUserName",userName);
        // 刚刚模糊查询的 roleId
        request.setAttribute("queryUserRole",roleid);
        // 查询出来的总数
        request.setAttribute("totalCount",userCount);
        // 当前页面
        request.setAttribute("currentPageNo",currentPageNo);
        // 总页数
        request.setAttribute("totalPageCount",totalPageCount);

        // 视图解析器：/WEB-INF/jsp/userlist.jsp
        return "userlist";
    }

    @GetMapping( "/viewUser/{userId}")
    public String viewUser(@PathVariable(name = "userId") int userId, Model model) {
        // UserService userService = Constants.context.getBean("userService", UserService.class);

        // 通过userId 查询出这个员工的信息，返回实体类user
        User user = userService.getUserById(userId);

        // 把user存入model，发给前端
        model.addAttribute("user",user);

        //user的userRoleName通过联表查询。通过user.userRole = role.id 联表

        // 视图解析器：/WEB-INF/jsp/userview.jsp
        return "userview";
    }


    @GetMapping("/toModifyUser/{userId}")
    public String toModifyUser(@PathVariable(name = "userId") int userId, Model model) {
        // UserService userService = Constants.context.getBean("userService", UserService.class);

        // 通过userId 查询出这个员工的信息，返回实体类user
        User user = userService.getUserById(userId);

        // 把user存入model，发给前端
        model.addAttribute("user",user);

        //user的userRoleName通过联表查询。通过user.userRole = role.id 联表

        // 视图解析器：/WEB-INF/jsp/usermodify.jsp
        return "usermodify";
    }

    @PostMapping("/modifyUser")
    @ResponseBody
    public void modifyUser(HttpServletRequest req, HttpServletResponse resp) {
        String id = req.getParameter("uid");
        String userName = req.getParameter("userName").trim();
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");


        // 把表单的信息封装到实体类user中
        User user = new User();
        user.setId(Integer.valueOf(id));
        user.setUserName(userName);
        user.setGender(Integer.valueOf(gender));
        try {
           /* System.out.println(birthday);*/
           /* System.out.println(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));*/

            // 设置birthday的格式
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());
        // UserService userService = Constants.context.getBean("userService", UserService.class);

        // 执行添加员工业务
        userService.modifyUser(user);
        try {
            // 重定向到 userList页面
            resp.sendRedirect("/user/userList");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/toPwdModify")
    public String toPwdModify(){
        return "pwdmodify";
    }

    @GetMapping("/checkPwd")
    @ResponseBody
    public Map checkPwd(HttpServletRequest request, HttpSession session) {
        User user = (User) session.getAttribute(Constants.USER_SESSION);
        // 从前端表单获取旧密码
        String oldpassword = request.getParameter("oldpassword");
        // 创建工具map
        HashMap<String, String> resultMap = new HashMap<>();
        if (user == null) {
            // 如果session过期了，就报错
            resultMap.put("result","sessionerror");
        } else {
            // 如果密码为空，报错
            if (StringUtils.isNullOrEmpty(oldpassword)) {
                resultMap.put("result","error");

            } else {
                // 从userSession中获取用户密码
                if (user.getUserPassword().equals(oldpassword)) {
                // 如果密码正确，给前端返回true信息
                    resultMap.put("result", "true");
                } else {
                    // 如果密码错误，给前端返回false信息
                    resultMap.put("result", "false");
                }
            }
        }return resultMap;
    }

    @PostMapping("/modifyPwd")
    @ResponseBody
    public void modifyPwd(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException {
        // 从session中获取user信息
        User user = (User) session.getAttribute(Constants.USER_SESSION);
        // 从表单获取新密码
        String newpassword = request.getParameter("newpassword");
        Integer id = user.getId();
        HashMap<String, String> resultMap = new HashMap<>();

        // 从容器中获取userService
        //UserService userService = Constants.context.getBean("userService", UserService.class);
        // 执行业务，修改user的密码
        int i = userService.modifyPassword(id, newpassword);

        if (i > 0) {
            // 返回密码修改成功信息给前端
            request.setAttribute("message","密码修改成功，请重新登录");
            // 修改密码成功后，移除session的user，让用户重新登录
            request.getSession().removeAttribute(Constants.USER_SESSION);
            response.sendRedirect("/user/login");

        } else {
            // 密码修改出现异常，返回修改页面
            request.setAttribute("message","密码修改不成功,新密码有问题");
            request.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(request,response);
        }
    }


    @RequestMapping("/toUserAdd")
    public String toUserAdd() {
        return "useradd";
    }

    @RequestMapping("/checkUserCode")
    @ResponseBody
    public String checkUserCode(HttpServletRequest req) {
        //UserService userService = Constants.context.getBean("userService", UserService.class);

        // 创建一个工具类 resultMap
        HashMap<String , String > resultMap = new HashMap<>();

        // 从表单中获取userCode
        String userCode = req.getParameter("userCode").trim();
        if(StringUtils.isNullOrEmpty(userCode)){

            // userCode不能为空
            resultMap.put("userCode","exist");
        }
        else {

            // 检查这个userCode是否已经存在数据库中
            List<User> i = userService.checkUserCode(userCode);

            if(i.size() > 0){

                // 说明该userCode已经存在数据库，把exist信息存入工具resultMap
                resultMap.put("userCode","exist");
            }else {
                // 如果不存在相同的userCode，就添加该user，把notExist信息存入工具resultMap
                resultMap.put("userCode","notExist");
            }
        }
        // jackson 工具类 把工具类map转成Jason字符串，返回给前端
        ObjectMapper objectMapper = new ObjectMapper();
        String s = null;
        try {
            s = objectMapper.writeValueAsString(resultMap);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "";
        }return s;
    }

    @PostMapping("/userAdd")
    @ResponseBody
    public void userAdd(HttpServletRequest req, HttpServletResponse resp) {
/*        String id = req.getParameter("uid");*/
        String userCode = req.getParameter("userCode");
        String userName = req.getParameter("userName");
        String userPassword = req.getParameter("userPassword");
        String gender = req.getParameter("gender");
        String birthday = req.getParameter("birthday");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String userRole = req.getParameter("userRole");


        User user = new User();
/*        user.setId(Integer.valueOf(id));*/
        user.setUserCode(userCode);
        user.setUserName(userName);
        user.setUserPassword(userPassword);
        user.setGender(Integer.valueOf(gender));
        try {
            user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(birthday));
        } catch (ParseException e) {

            e.printStackTrace();
        }

        user.setPhone(phone);
        user.setAddress(address);
        user.setUserRole(Integer.valueOf(userRole));
        user.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        user.setCreationDate(new Date());

        //UserService userService = Constants.context.getBean("userService", UserService.class);
        // 执行业务代码，添加user
        userService.userAdd(user);

        try {
            // 重定向到/user/userList，展示user
            resp.sendRedirect("/user/userList");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @RequestMapping("/deleteUser/{userId}")
    @ResponseBody
    public String deleteUser(@PathVariable(name = "userId") int userId, HttpServletResponse response) {
        //UserService userService = Constants.context.getBean("userService", UserService.class);

        // 创建一个工具 map
        HashMap<String, String> resultMap = new HashMap<>();

        // 定位需要删除的user
        if (StringUtils.isNullOrEmpty(String.valueOf(userId))) {
            // 如果userId为空，就通过工具map返回notExist信息给前端
            resultMap.put("delResult","notExist");
        } else {
            // 如果userId不为空，就删除该user
            int i = userService.deleteUser(userId);
            if (i > 0) {
                //
                //System.out.println("删除成功" + userId);
                // 删除成功，就通过工具map返回true信息给前端
                resultMap.put("delResult","true");
            } else {
                // 删除成功，就通过工具map返回false信息给前端
                resultMap.put("delResult","false");
            }
        }
        // jackson 工具类 把工具类map转成Jason字符串，返回给前端
        ObjectMapper objectMapper = new ObjectMapper();
        String s = null;
        try {
            s = objectMapper.writeValueAsString(resultMap);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return s;

    }


    @RequestMapping("/logOut")
    @ResponseBody
    public void logOut(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().removeAttribute(Constants.USER_SESSION);

        try {
            response.sendRedirect(request.getContextPath()+"/login.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

/*    @Test
    public void test(){
*//*        System.out.println("context.hashCode()========>"+Constants.context.hashCode());
        Map<String, Object> map11 = new HashMap<>();
        map11.put("userName",null);
        map11.put("userRole",0);
        map11.put("currentPageNo",0);
        map11.put("PageSize",5);*//*

        UserService userService = Constants.context.getBean("userService", UserService.class);

        User user = userService.getUserById(20);
        System.out.println(user);


*//*        for (int i = 0; i < 20; i++) {
            UserService userService = Constants.context.getBean("userService", UserService.class);
            System.out.println("userService.hashCode()========>"+userService.hashCode());

            RoleService roleService = Constants.context.getBean("roleService", RoleService.class);
            System.out.println("roleService.hashCode()========>"+roleService.hashCode());

            BillService billService = Constants.context.getBean("billService", BillService.class);
            System.out.println("billService.hashCode()========>"+billService.hashCode());

            ProviderService providerService = Constants.context.getBean("providerService", ProviderService.class);
            System.out.println("providerService.hashCode()========>"+providerService.hashCode());
        }*//*

    }*/
}
